package com.scalesoft.artsync.modelimpl.submission;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;

import com.scalesoft.artsync.model.submission.Submission;
import com.thoughtworks.xstream.XStream;

public class SubmissionCollection {

	private ArrayList<Submission> submissions;
	private static SubmissionCollection instance = null;
	private static final String saveFilename = "data.xml";
	
	public static SubmissionCollection getInstance() {
		if (instance == null) {
			instance = new SubmissionCollection(new ArrayList<Submission>());
		}
		return instance;
	}

	public SubmissionCollection (ArrayList<Submission> submissions) {
		this.submissions = submissions;
	}

	public ArrayList<Submission> getSubmissions() {
		return submissions;
	}

	public void setSubmissions(ArrayList<Submission> submissions) {
		this.submissions = submissions;
	}
	
	// -----------------------------------------------------------------
	// Utility Functions
	// -----------------------------------------------------------------

	private static String readFile(String filename) throws Exception {
		FileReader fr = new FileReader(filename);
		BufferedReader br = new BufferedReader(fr);
		String line;
		StringBuilder result = new StringBuilder();
		while ((line = br.readLine()) != null) {
			result.append(line);
		}
		fr.close();
		return result.toString();
	}

	private static void writeFile(String filename, String data) throws Exception {
		FileWriter fw = new FileWriter(filename);
		fw.write(data);
		fw.close();
	}

	public static ArrayList<Submission> loadSubmissionData() {
		ArrayList<Submission> data = new ArrayList<Submission>();
		try {
			File f = new File(saveFilename);
			if (f.exists()) {
				XStream xstream = new XStream();
				xstream.omitField(SubmissionCollection.class, "instance");
				String xmlData = readFile(saveFilename);
				instance = (SubmissionCollection) xstream.fromXML(xmlData);
				data = instance.getSubmissions();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return data;
	}

	public static void saveSubmissionData(ArrayList<Submission> data) throws Exception {
		instance.setSubmissions(data);
		XStream xstream = new XStream();
		xstream.omitField(SubmissionCollection.class, "instance");
		String xmlData = xstream.toXML(instance);
		writeFile(saveFilename, xmlData);
	}

	
}
